<template>
  <div class="notification-management">
    <div class="operation-bar">
      <div class="search-filters">
        <el-input
          v-model="searchQuery"
          placeholder="搜索通知内容..."
          style="width: 300px"
          clearable
          @keyup.enter="searchNotifications"
        >
          <template #append>
            <el-button :icon="Search" @click="searchNotifications"></el-button>
          </template>
        </el-input>
        <el-select v-model="notificationType" placeholder="通知类型" clearable @change="filterByType">
          <el-option label="文档更新" value="document_update"></el-option>
          <el-option label="新文档" value="document_new"></el-option>
          <el-option label="系统通知" value="system"></el-option>
        </el-select>
        <el-select v-model="readStatus" placeholder="阅读状态" clearable @change="filterByReadStatus">
          <el-option label="全部" value="all"></el-option>
          <el-option label="已读" value="read"></el-option>
          <el-option label="未读" value="unread"></el-option>
        </el-select>
      </div>
      <el-button type="primary" @click="showCreateNotificationDialog">发送系统通知</el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="notifications.length === 0" class="empty-container">
      <el-empty description="暂无通知数据" />
    </div>
    
    <el-table v-else :data="notifications" style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="接收用户" width="120"></el-table-column>
      <el-table-column label="通知类型" width="120">
        <template #default="scope">
          <el-tag :type="getNotificationTypeTag(scope.row.type)">
            {{ getNotificationTypeName(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="150"></el-table-column>
      <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip></el-table-column>
      <el-table-column label="发送时间" width="180">
        <template #default="scope">
          {{ new Date(scope.row.createTime).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.readStatus === 'read' ? 'success' : 'info'" size="small">
            {{ scope.row.readStatus === 'read' ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small" @click="viewNotificationDetail(scope.row)">查看</el-button>
          <el-button size="small" type="danger" @click="deleteNotification(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="batch-actions" v-if="notifications.length > 0">
      <el-button :disabled="selectedNotifications.length === 0" @click="markAsRead">标记为已读</el-button>
      <el-button :disabled="selectedNotifications.length === 0" type="danger" @click="batchDeleteNotifications">批量删除</el-button>
    </div>

    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 通知详情对话框 -->
    <el-dialog v-model="notificationDetailVisible" title="通知详情" width="40%">
      <div v-if="currentNotification">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ currentNotification.id }}</el-descriptions-item>
          <el-descriptions-item label="接收用户">{{ currentNotification.username }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentNotification.userId }}</el-descriptions-item>
          <el-descriptions-item label="通知类型">{{ getNotificationTypeName(currentNotification.type) }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ currentNotification.title }}</el-descriptions-item>
          <el-descriptions-item label="内容">{{ currentNotification.content }}</el-descriptions-item>
          <el-descriptions-item label="发送时间">{{ new Date(currentNotification.createTime).toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="阅读状态">{{ currentNotification.readStatus === 'read' ? '已读' : '未读' }}</el-descriptions-item>
          <el-descriptions-item v-if="currentNotification.readStatus === 'read'" label="阅读时间">
            {{ new Date(currentNotification.readTime).toLocaleString() }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentNotification.documentId" label="相关文档">
            文档ID: {{ currentNotification.documentId }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 创建系统通知对话框 -->
    <el-dialog v-model="createNotificationVisible" title="发送系统通知" width="50%">
      <el-form :model="notificationForm" :rules="notificationRules" ref="notificationFormRef" label-width="100px">
        <el-form-item label="接收对象" prop="receiverType">
          <el-radio-group v-model="notificationForm.receiverType">
            <el-radio label="all">所有用户</el-radio>
            <el-radio label="specific">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="notificationForm.receiverType === 'specific'" label="选择用户" prop="userIds">
          <el-select
            v-model="notificationForm.userIds"
            multiple
            filterable
            placeholder="请选择用户"
            style="width: 100%"
          >
            <el-option v-for="user in userOptions" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="notificationForm.title" placeholder="请输入通知标题"></el-input>
        </el-form-item>
        
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="notificationForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入通知内容"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="重要程度">
          <el-rate v-model="notificationForm.importance" :max="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createNotificationVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNotification" :loading="submitting">发送</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和筛选
const searchQuery = ref('')
const notificationType = ref('')
const readStatus = ref('all')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据和状态
const loading = ref(true)
const notifications = ref([])
const selectedNotifications = ref([])
const currentNotification = ref(null)

// 对话框控制
const notificationDetailVisible = ref(false)
const createNotificationVisible = ref(false)
const submitting = ref(false)
const notificationFormRef = ref(null)

// 通知表单
const notificationForm = reactive({
  receiverType: 'all',
  userIds: [],
  title: '',
  content: '',
  importance: 1
})

// 表单验证规则
const notificationRules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' }
  ],
  userIds: [
    { required: true, message: '请选择至少一个用户', trigger: 'change', type: 'array' }
  ]
}

// 用户选项（模拟数据）
const userOptions = ref(Array.from({ length: 20 }, (_, i) => ({
  id: i + 1,
  name: `用户${i + 1}`
})))

// 初始化
onMounted(() => {
  fetchNotifications()
})

// 获取通知列表
async function fetchNotifications() {
  loading.value = true
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/admin/notifications', {
    //   params: {
    //     page: currentPage.value,
    //     size: pageSize.value,
    //     query: searchQuery.value,
    //     type: notificationType.value,
    //     status: readStatus.value
    //   }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    notifications.value = Array.from({ length: 10 }, (_, i) => {
      const types = ['document_update', 'document_new', 'system']
      const type = types[Math.floor(Math.random() * types.length)]
      const readStatuses = ['read', 'unread']
      const status = readStatuses[Math.floor(Math.random() * readStatuses.length)]
      
      return {
        id: i + 1,
        userId: Math.floor(Math.random() * 20) + 1,
        username: `user${Math.floor(Math.random() * 20) + 1}`,
        type: type,
        title: `${type === 'document_update' ? '文档更新' : type === 'document_new' ? '新文档' : '系统通知'} ${i + 1}`,
        content: `这是一条${type === 'document_update' ? '文档更新' : type === 'document_new' ? '新文档' : '系统通知'}通知，内容详情请点击查看。`,
        createTime: new Date().getTime() - Math.floor(Math.random() * 10000000),
        readStatus: status,
        readTime: status === 'read' ? new Date().getTime() - Math.floor(Math.random() * 5000000) : null,
        documentId: type !== 'system' ? Math.floor(Math.random() * 50) + 1 : null
      }
    })
    
    // 根据筛选条件过滤
    if (notificationType.value) {
      notifications.value = notifications.value.filter(item => item.type === notificationType.value)
    }
    
    if (readStatus.value !== 'all') {
      notifications.value = notifications.value.filter(item => item.readStatus === readStatus.value)
    }
    
    total.value = 100 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch notifications:', error)
    ElMessage.error('获取通知列表失败')
  } finally {
    loading.value = false
  }
}

// 获取通知类型显示名称
function getNotificationTypeName(type) {
  switch (type) {
    case 'document_update':
      return '文档更新'
    case 'document_new':
      return '新文档'
    case 'system':
      return '系统通知'
    default:
      return '未知类型'
  }
}

// 获取通知类型标签颜色
function getNotificationTypeTag(type) {
  switch (type) {
    case 'document_update':
      return 'success'
    case 'document_new':
      return 'primary'
    case 'system':
      return 'info'
    default:
      return 'info'
  }
}

// 表格选择变化
function handleSelectionChange(selection) {
  selectedNotifications.value = selection
}

// 搜索通知
function searchNotifications() {
  currentPage.value = 1
  fetchNotifications()
}

// 按类型筛选
function filterByType() {
  currentPage.value = 1
  fetchNotifications()
}

// 按阅读状态筛选
function filterByReadStatus() {
  currentPage.value = 1
  fetchNotifications()
}

// 分页处理
function handleSizeChange(size) {
  pageSize.value = size
  fetchNotifications()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchNotifications()
}

// 查看通知详情
function viewNotificationDetail(notification) {
  currentNotification.value = { ...notification }
  notificationDetailVisible.value = true
}

// 删除通知
async function deleteNotification(id) {
  try {
    await ElMessageBox.confirm('确定要删除此通知吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/admin/notifications/${id}`)
    
    // 模拟删除成功
    notifications.value = notifications.value.filter(n => n.id !== id)
    total.value--
    
    ElMessage.success('通知删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete notification:', error)
      ElMessage.error('删除通知失败')
    }
  }
}

// 批量标记为已读
async function markAsRead() {
  try {
    if (selectedNotifications.value.length === 0) return
    
    // 这里替换为实际的API调用
    // const ids = selectedNotifications.value.map(item => item.id)
    // await axios.put('/api/admin/notifications/read', { ids })
    
    // 模拟标记为已读
    selectedNotifications.value.forEach(notification => {
      const index = notifications.value.findIndex(n => n.id === notification.id)
      if (index !== -1) {
        notifications.value[index].readStatus = 'read'
        notifications.value[index].readTime = new Date().getTime()
      }
    })
    
    ElMessage.success('标记为已读成功')
  } catch (error) {
    console.error('Failed to mark as read:', error)
    ElMessage.error('标记为已读失败')
  }
}

// 批量删除通知
async function batchDeleteNotifications() {
  try {
    if (selectedNotifications.value.length === 0) return
    
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedNotifications.value.length} 条通知吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // const ids = selectedNotifications.value.map(item => item.id)
    // await axios.delete('/api/admin/notifications', { data: { ids } })
    
    // 模拟删除成功
    const deleteIds = selectedNotifications.value.map(n => n.id)
    notifications.value = notifications.value.filter(n => !deleteIds.includes(n.id))
    total.value -= selectedNotifications.value.length
    selectedNotifications.value = []
    
    ElMessage.success('批量删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to batch delete notifications:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 显示创建系统通知对话框
function showCreateNotificationDialog() {
  // 重置表单
  notificationForm.receiverType = 'all'
  notificationForm.userIds = []
  notificationForm.title = ''
  notificationForm.content = ''
  notificationForm.importance = 1
  
  createNotificationVisible.value = true
}

// 提交创建通知表单
async function submitNotification() {
  if (!notificationFormRef.value) return
  
  await notificationFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 这里替换为实际的API调用
        // const params = {
        //   receiverType: notificationForm.receiverType,
        //   title: notificationForm.title,
        //   content: notificationForm.content,
        //   importance: notificationForm.importance
        // }
        // if (notificationForm.receiverType === 'specific') {
        //   params.userIds = notificationForm.userIds
        // }
        // await axios.post('/api/admin/notifications/system', params)
        
        // 模拟发送成功
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('通知发送成功')
        createNotificationVisible.value = false
        fetchNotifications() // 刷新列表
      } catch (error) {
        console.error('Failed to send notification:', error)
        ElMessage.error('通知发送失败')
      } finally {
        submitting.value = false
      }
    }
  })
}
</script>

<style scoped>
.notification-management {
  width: 100%;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-filters {
  display: flex;
  gap: 15px;
}

.batch-actions {
  margin: 15px 0;
  display: flex;
  gap: 10px;
}

.loading-container, 
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>